<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\facade\Mns;
use app\models\{Annou, Banner, News, Riderlist, Region, Config, Annous, Tels, IntergralGoods};
use think\facade\Log;
use think\facade\Env;


use think\Db;

class Other extends Base
{
    public function Annou()
    {
        $type = $this->request->get('type/d', 1);
        $list = (new Annou())->order('dates desc')->where('type', $type)->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }

    public function add_goods()
    {
        $goodsid = $this->request->get('id/d', 0);
        if (empty($goodsid)) {
            $this->result([], 1, '获取失败');
        }
        $cateid = $this->request->get('cateid/d', 0);
        $sku = $this->request->get('sku/d', 0);
        $sales = $this->request->get('sales/d', 0);
        $id = $this->request->get('id/d', 0);
        $url = 'http://api.daicuo.cc/tbkxiangqing/?token=aa4c728156592238bfc4406dab3616bc&id=' . $goodsid;
        $res = getData($url);
        if ($res['code'] == 200) {
            $data = $res['data'];
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date('Ymd');
            $rrr =  getImage($data['pict_url'], $path, '', 0);
            if (!empty($rrr['file_name'])) {
                $images[] = 'https://' . Env::get('app.api_url') . "/uploads/" . date('Ymd') . '/' . $rrr['file_name'];
            }
            foreach ($data['small_images']['string'] as $v) {
                $rrrm =  getImage($v, $path, '', 0);
                if (!empty($rrrm['file_name'])) {
                    $detail[] = 'https://' . Env::get('app.api_url') . "/uploads/" . date('Ymd') . '/' . $rrrm['file_name'];
                }
            }
            if (count($images) == 0) {
                $this->result([], 1, '获取失败');
            }
            if (count($detail) == 0) {
                $this->result([], 1, '获取失败');
            }
            $images = json_encode($images, true);
            $detail = json_encode($detail, true);
            $save = [
                'title' => $data['title'],
                'shortitle' => $data['title'],
                'price' => $data['zk_final_price'],
                'intergral' => $data['zk_final_price'] * 3 + 20,
                'images' => $images,
                'detail' => $detail,
                'cateid' => $cateid,
                'sku' => $sku,
                'sales' => $sales
            ];
            if (!empty($id)) {
                $res = (new IntergralGoods())->allowfield(true)->save($save, ['id' => $id]);
            } else {
                $res = (new IntergralGoods())->allowfield(true)->save($save);
            }

            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '获取失败');
        }
    }


    public function Annous()
    {
        $streetid = $this->request->get('streetid/d', 0);
        if (empty($streetid)) {
            $this->result([], 0, '获取成功');
        }
        $result = (new Annous())->field('title,content')->where('streetid', $streetid)->find();
        if (empty($result)) {
            $areatops = (new Region())->where('id', $streetid)->find();
            $areatop = $areatops['area_code'] ?? 0;
            $result = (new Annous())->field('title,content')->where('areaid', $areatop)->find();
        }
        $this->result($result, 0, '获取成功');
    }

    public function Banner()
    {
        $streetid = $this->request->get('areaid/d', 0);
        Log::write('编码：' . $streetid, 'banner');
        $street = (new Region())->where(['id' => $streetid, 'level' => 4])->find();
        $area = (new Region())->where(['area_code' => $street['area_code'], 'level' => 3])->find();
        $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
        $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
        $where = [
            'provinceid' => $province['area_code'] ?? 0,
            'cityid' => 0,
            'areaid' => 0,
            'streetid' => 0
        ];
        $where1 = [
            'cityid' => $city['area_code'] ?? 0,
            'areaid' => 0,
            'streetid' => 0
        ];
        $where2 = [
            'areaid' => $area['area_code'] ?? 0,
            'streetid' => 0
        ];
        $where5 = [
            'streetid' => $streetid
        ];
        $where3 = [
            'provinceid' => 0,
            'cityid' => 0,
            'areaid' => 0,
            'streetid' => 0
        ];
        $list = (new Banner())->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        })->whereOr(function ($query) use ($where2) {
            $query->where($where2);
        })->whereOr(function ($query) use ($where5) {
            $query->where($where5);
        })->whereOr(function ($query) use ($where3) {
            $query->where($where3);
        })->select();
        $this->result($list, 0, '获取成功');
    }


    public function Tels()
    {
        $areaid = $this->request->get('areaid/d', 0);
        $list = (new Tels())->where(['areaid' => $areaid])->value('name');
        $this->result($list, 0, '获取成功');
    }

    public function News()
    {
        $type = $this->request->get('type/d', 1);
        $list = (new News())->order('dates desc')->where('type', $type)->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }

    public function Newsdetail()
    {
        $id = $this->request->get('id/d', 1);
        $list = (new News())->where('id', $id)->find();
        $this->result($list, 0, '获取成功');
    }
    //发送短信
    public function sendMns()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
        ], [
            'mobile.require' => '手机号码必须填写',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where(['mobile' => $data['mobile']])->find();
        if (empty($user)) {
            $this->result([], 1, '您还不是骑手');
        }
        $CheckCode = (new Mns())->send($data['mobile']);
        if (!$CheckCode) {
            $this->result([], 1, $CheckCode['msg']);
        }
        $this->result([], 0, $CheckCode['msg']);
    }

    public function uploads()
    {
        if ($this->request->isPost()) {
            $file = request()->file('file');
            if (empty($file)) {
                $this->result([], 1, '上传失败');
            }
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
            $info = $file->validate(['size' => 1024 * 1024 * 50, 'ext' => 'jpg,png,gif,jpeg'])
                ->move($path);
            if (!$info) {
                $this->result([], 1, $file->getError());
            } else {
                $url = '/uploads' . '/' . $info->getSaveName();
                $url = url($url, '', '', true);
                $this->result($url, 0, '上传成功');
            }
        }
    }

    public function appconfig()
    {
        $result = (new Config())->where(['key_value' => ['Version', 'Android', 'Ios', 'Ermm', 'Privacy']])->select();
        $this->result($result, 0, '获取成功');
    }


    //腾讯接口
    public function geocoder1()
    {
        $key = '2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT';
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $url = 'https://apis.map.qq.com/ws/geocoder/v1/?key=' . $key . '&location=' . $data['lat'] . ',' . $data['lng'] . '&poi_options=policy=4';
            $res = getData($url);
            if ($res['status'] == 0) {
                if (!empty($res['result']['ad_info'])) {
                    if (!empty($res['result']['address_reference']['town'])) {
                        //获取街道信息
                        $street_id = (new Region())
                            ->where(['level' => 4])
                            ->where('area_code', 'like', '%' . $res['result']['ad_info']['adcode'] . '%')
                            ->where('name|remark', 'like', '%' . $res['result']['address_reference']['town']['title'] . '%')->find();
                        if (empty($street_id)) {
                            $street_id = (new Region())
                                ->where('code', 'like', '%' . $res['result']['address_reference']['town']['id'] . '%')->find();
                        }
                        if (empty($street_id)) {
                            $township = mb_substr($res['result']['address_reference']['town']['title'], 0, 2, 'utf-8');
                            $street_id = (new Region())
                                ->where(['level' => 4])
                                ->where('area_code', 'like', '%' . $res['result']['ad_info']['adcode'] . '%')
                                ->where('name|remark', 'like', '%' . $township . '%')->find();
                        }
                        $res['result']['ad_info']['street'] = $street_id['id'] ?? 0;
                        $res['result']['ad_info']['street_title'] = $street_id['name'] ?? $res['result']['address_reference']['town']['title'];
                        if (!empty($street_id)) {
                            $res['result']['ad_info']['district'] = (new Region())
                                ->where(['id' => $street_id['parent_id']])->value('name');
                        }
                    }
                    Log::write('==============地址分割线=============', 'weizhi');
                    Log::write($data, 'weizhi');
                    Log::write($res['result']['ad_info'], 'weizhi');
                    Log::write('==============地址分割线=============', 'weizhi');
                    $this->result($res['result']['ad_info'], 0, '获取成功');
                } else {
                    $this->result([], 1, '编号有误');
                }
            } else {
                $this->result([], 1, $res['message']);
            }
        } else {
            $this->result([], 1, ['key' => $key]);
        }
    }

    //高德接口
    public function geocoder()
    {
        $key = '2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT';
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            Log::write('==============地址分割线=============', 'weizhi');
            Log::write($data, 'weizhi');
            $url = 'https://restapi.amap.com/v3/geocode/regeo?location=' . $data['lng'] . ',' . $data['lat'] . '&key=ac9bfdc24e033d01cf7b18cd9a15ffca';
            $res = getData($url);
            Log::write($res, 'weizhi');
            Log::write('==============地址分割线=============', 'weizhi');
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败');
                }
                $results = $res['regeocode']['addressComponent'];
                if (is_array($results['district'])) {
                    $results['district'] = '';
                }
                $resuls = [
                    "nation_code" => 156,
                    "adcode" => $results['adcode'] ?? 0,
                    "city_code" => "156" . $results['adcode'] ?? 0,
                    "name" => "中国," . $results['province'] . ',' . $results['city'] . ',' . $results['district'] ?? '',
                    "location" => [
                        "lat" => $data['lat'],
                        "lng" => $data['lng']
                    ],
                    "nation" => "中国",
                    "province" => $results['province'] ?? '',
                    "city" => $results['city'] ?? '',
                    "district" => $results['district'] ?? '',
                    "street" => 0,
                    "street_title" => $results['township'] ?? ''
                ];
                $street_id = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', $resuls['adcode'])
                    ->where('name|remark', 'like', '%' . $resuls['street_title'] . '%')->find();
                if (empty($street_id)) {
                    $township = mb_substr($resuls['street_title'], 0, 2, 'utf-8');
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('name|remark', 'like', '%' . $township . '%')->find();
                }
                //通过名字查找不到街道再通过编号查找
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('code', substr($results['towncode'], 0, 9))->find();
                }
                $resuls['street'] = $street_id['id'] ?? 0;
                $resuls['street_title'] = $street_id['name'] ?? $resuls['street_title'];
                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 1, ['key' => $key]);
        }
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }
}
